﻿using System;
using System.Collections.Generic;
using System.Text;
using DoxygenBrowser.Common.InOut;
using DoxygenBrowser.Common.Model;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using DoxygenBrowserAddin.Data;

namespace DoxygenBrowserAddin.Controller
{
  public class TDictionaryFileLoader : ITDictionaryFileVisitor
  {
    private TokenDictionary _tokenDictionary;

    public TokenDictionary TokenDictionary
    {
      get { return _tokenDictionary; }
    }
    private string _strPath;



    public event EventHandler TokenDictionaryLoaded;

    public TDictionaryFileLoader(string strPath)
    {
      _strPath = strPath;
      _tokenDictionary = new TokenDictionary();
    }

    public void Load()
    {
      TDictionaryFile tDictionaryFile = null;

      using (Stream stream = File.Open(_strPath, FileMode.Open))
      {
        BinaryFormatter bformatter = new BinaryFormatter();
        tDictionaryFile = (TDictionaryFile)bformatter.Deserialize(stream);
        stream.Close();
      }

      tDictionaryFile.AcceptVisitor(this);

      OnTokenDictionaryLoaded();
    }

    private void OnTokenDictionaryLoaded()
    {
      if (TokenDictionaryLoaded != null)
      {
        TokenDictionaryLoaded(this, EventArgs.Empty);
      }
    }


    #region ITDictionaryFileVisitor Members

    public void VisitEntry(string strKey, string strPath, string strAnchor)
    {
      _tokenDictionary.AddTokenEntry(strKey, new FileLocation(strPath, strAnchor));
    }

    #endregion
  }
}
